package com.blog.serlvet;

import com.alibaba.fastjson.JSONObject;
import com.blog.bean.BaseResponse;
import com.blog.bean.Comment;
import com.blog.bean.User;
import com.blog.dao.CommentDao;
import com.blog.util.LoginUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class CommentListServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = LoginUtil.checkApiLogin(session, resp);
        if (user == null) {
            return;
        }

        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter writer = resp.getWriter();

        // 获取参数
        Integer blogId = null;
        try {
            blogId = Integer.valueOf(req.getParameter("id"));
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(JSONObject.toJSONString(new BaseResponse(400, "参数错误", null)));
            return;
        }

        CommentDao commentDao = new CommentDao();
        List<Comment> list;
        try {
            list = commentDao.select(blogId);
        } catch (Exception e) {
            resp.sendError(500);
            return;
        }
        writer.println(JSONObject.toJSONString(new BaseResponse(200, "获取评论成功", list)));
    }
}
